/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BackingBeans;

import Facebook.FacebookClientLocal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import smartgrid.Contracts;
import smartgrid.FacebookAccountInterface;
import smartgrid.FacebookAccountManager;
import smartgrid.Supplier;
import smartgrid.SuppliersInfo;
import smartgrid.exceptions.ContractAlreadyExistsException;
import smartgrid.exceptions.FacebookAccountNotExistException;
import smartgrid.exceptions.InvalidContractNifException;
import smartgrid.exceptions.InvalidContractNumberException;

/**
 *
 * @author andre
 */
@ManagedBean
@RequestScoped
public class UnregisteredBackingBean {
    private Map<String, Supplier> Suppliers;
    private String SelectedSupplier;
    
    private String Contract;
    private String Nif;
    
    /** Creates a new instance of UnregisteredBackingBean */
    public UnregisteredBackingBean() {
        this.Suppliers = new HashMap<String, Supplier>();
        try {
            InitialContext initCtx = new InitialContext();
            SuppliersInfo si = (SuppliersInfo)initCtx.lookup("java:global/SmartGridEA/SuppliersManager");
            
            List<Supplier> ss = si.getSuppliers();
            if(ss != null){
                System.out.println("NOT NULL");
                for(Supplier s : ss){
                    this.Suppliers.put(s.getName(), s);
                }
            }
        } catch (NamingException ex) {
            Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getSelectedSupplier() {
        return SelectedSupplier;
    }

    public void setSelectedSupplier(String SelectedSupplier) {
        this.SelectedSupplier = SelectedSupplier;
    }
    
    public Set<String> getSuppliersList() {
        return Suppliers.keySet();
    }

    public String getContract() {
        return Contract;
    }

    public void setContract(String Contract) {
        this.Contract = Contract;
    }

    public String getNif() {
        return Nif;
    }

    public void setNif(String Nif) {
        this.Nif = Nif;
    }
    
    private boolean validateEmpty(){
        boolean ret = true;
        FacesContext ctx = FacesContext.getCurrentInstance();
        
        if(this.Contract == null || this.Contract.isEmpty()){
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve preencher o número do contrato.");
            msg.setDetail("Deve preencher o número do contrato."); 
            ctx.addMessage("contractform:contract", msg);
            ret = false;
        }
        
        if(this.Nif == null || this.Nif.isEmpty()){
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve preencher o número de contribuinte.");
            msg.setDetail("Deve preencher o número de contribuinte."); 
            ctx.addMessage("contractform:nif", msg);
            ret = false;
        }
        return ret;
    }
    
    public String submit(){
        FacesContext ctx = FacesContext.getCurrentInstance();
        if(!this.validateEmpty())       
            return "";
        else{
            try {
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
                FacebookClientLocal fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
                if(fbl == null){
                    return "error";
                }
                
                InitialContext initCtx = new InitialContext();
                FacebookAccountInterface fb = (FacebookAccountInterface)initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");
                
                Contracts cm = (Contracts)initCtx.lookup("java:global/SmartGridEA/ContractsManager");
                
                fb.insertFacebookAccount(fbl.getUId(), fbl.getNome(), "");
                
                Supplier s = this.Suppliers.get(this.SelectedSupplier);
                try {
                    cm.addContractToFacebookAccount(fbl.getUId(), s.getID(), this.Contract, this.Nif);
                } catch (InvalidContractNifException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O Nif não corresponde a este contrato.");
                    msg.setDetail("O Nif não corresponde a este contrato."); 
                    ctx.addMessage("contractform:nif", msg);
                    return "";
                } catch (InvalidContractNumberException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O contrato que inseriu não é válido.");
                    msg.setDetail("O contrato que inseriu não é válido."); 
                    ctx.addMessage("contractform:contract", msg);
                    return "";
                } catch (ContractAlreadyExistsException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O contrato que inseriu já está associado à conta facebook.");
                    msg.setDetail("O contrato que inseriu já está associado à conta facebook."); 
                    ctx.addMessage("contractform:contract", msg);
                    return "";
                } catch(FacebookAccountNotExistException ex){
                    return "error";
                }
                
            } catch (NamingException ex) {
                Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
            }
            return "index";
        }
    }
}
